using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlServerCe;
using System.Diagnostics;
using System.IO;
using Christian.Helle.PocketNews.PocketPC.NewsProtocol;

namespace Christian.Helle.PocketNews.PocketPC.Data
{
	public static class Cache
	{
		private static string conn_str;
		private static DbConnection conn = null;

        public static DbConnection Connection
		{
			get
			{
				if (conn == null) {
#if DEBUG
					int start = Environment.TickCount;
#endif
					Debug.WriteLine("DatabaseConnection is NULL");
					Debug.WriteLine("Initializing Connection");

					try {
						Debug.WriteLine("Unlocking Application Database if in case the file is READ ONLY");

						var engine = new DatabaseEngine();
						engine.CheckApplicationDatabase();
						conn_str = engine.ConnectionString;
					}
					catch (FileNotFoundException e) {
						Debug.Assert(false, e.Message, e.StackTrace);

						ErrorLog.AppendError(
							"FileNotFoundException at DatabaseCache::DatabaseConnection",
							e.Message,
							e.StackTrace);

						return null;
					}

					Debug.WriteLine("Openning a database connection");

					conn = new SqlCeConnection(conn_str);
					conn.Open();
#if DEBUG
					Debug.WriteLine(
						string.Format("Loading Database Connection took: {0}", Environment.TickCount - start));
#endif
				}
				return conn;
			}
		}

		public static void CloseConnections()
		{
			if (conn != null && conn.State != ConnectionState.Closed) {
				conn.Close();
				conn.Dispose();
				conn = null; 
			}
		}

		private static List<ArticleHeader> articleCollection;
		public static List<ArticleHeader> ArticleCollection
		{
			get
			{
				if (articleCollection == null)
				{
					articleCollection = new List<ArticleHeader>();
				}
				return articleCollection;
			}
			set { articleCollection = value; }
		}

		private static List<ArticleHeader> newArticles;
		public static List<ArticleHeader> NewArticles
		{
			get
			{
				if (newArticles == null)
				{
					newArticles = new List<ArticleHeader>();
				}
				return newArticles;
			}
			set { newArticles = value; }
		}

		private static List<Draft> drafts;
		public static List<Draft> Drafts
		{
			get
			{
				if (drafts == null)
				{
					drafts = new List<Draft>();
				}
				return drafts;
			}
			set { drafts = value; }
		}
	}
}
